package com.gan.simple_init.util;

import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.fastjson.JSON;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Excel工具类
 *
 * @author gbw
 */
public class ExcelUtil {
    /**
     * 构造复杂头，相当于@ExcelProperty({"bigTitle","header[index]"})；用自定义头的话EasyExcel的样式注解会失效
     */
    public static List<List<String>> buildHead(String[] header, String bigTitle) {
        List<String> head;
        List<List<String>> list = new LinkedList<>();
        for (String h : header) {
            head = new LinkedList<>();
            head.add(bigTitle);
            head.add(h);
            list.add(head);
        }
        return list;
    }

    /**
     * 构造复杂头，相当于@ExcelProperty("header[index]")；用自定义头的话EasyExcel的样式注解会失效
     */
    public static List<List<String>> buildHead(String[] header) {
        List<String> head;
        List<List<String>> list = new LinkedList<>();
        for (String h : header) {
            head = new LinkedList<>();
            head.add(h);
            list.add(head);
        }
        return list;
    }


    /**
     * 为合并的单元格设置样式（可根据需要自行调整）
     */
    public static void setRegionStyle(Sheet sheet, CellRangeAddress region, CellStyle cs) {
        for (int i = region.getFirstRow(); i <= region.getLastRow(); i++) {
            Row row = sheet.getRow(i);
            if (null == row) {
                row = sheet.createRow(i);
            }
            for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
                Cell cell = row.getCell(j);
                if (null == cell) {
                    cell = row.createCell(j);
                }
                cell.setCellStyle(cs);
            }
        }
    }

    /**
     * 自定义第一行样式
     *
     * @param height       行高
     * @param context
     * @param headerLength
     * @return
     */
    public static SheetWriteHandler buildFirstLine(short height, String context, int headerLength) {
        return new SheetWriteHandler() {
            @Override
            public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder
                    writeSheetHolder) {
                Workbook workbook = writeWorkbookHolder.getWorkbook();
                Sheet sheet = workbook.getSheetAt(0);
                //设置标题
                Row row1 = sheet.createRow(0);
                row1.setHeight(height);
                Cell cell = row1.createCell(0);
                //设置单元格内容
                cell.setCellValue(context);
                CellStyle cellStyle = workbook.createCellStyle();
                // 设置边框
                cellStyle.setBorderBottom(BorderStyle.THIN);
                cellStyle.setBorderLeft(BorderStyle.THIN);
                cellStyle.setBorderRight(BorderStyle.THIN);
                cellStyle.setBorderTop(BorderStyle.THIN);
                // 设置竖直居中
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                // 自动换行
                cellStyle.setWrapText(true);
                // 设置字体粗体，红色字体
                Font font = workbook.createFont();
                font.setBold(true);
                font.setColor(IndexedColors.RED.getIndex());
                font.setFontHeight((short) 300);
                cellStyle.setFont(font);

                // 合并第一行单元格为头长度
                CellRangeAddress cellAddresses = new CellRangeAddress(0, 0, 0, headerLength - 1);
                // 设置合并单元格的边框
                ExcelUtil.setRegionStyle(sheet, cellAddresses, cellStyle);
                sheet.addMergedRegionUnsafe(cellAddresses);
            }
        };
    }

    /**
     * 构造错误返回
     */
    public static void buildError(HttpServletResponse response, String errorMsg) throws IOException {
        // 重置response
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        Map<String, Object> map = MapUtils.newHashMap();
        map.put("code", -200);
        map.put("message", errorMsg);
        map.put("data", null);
        response.getWriter().println(JSON.toJSONString(map));
    }

    /**
     * 构造文件
     */
    public static void buildFile(HttpServletResponse response, String fileName) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }


}
